var globalCount = 0;
$(".top").click(function() {
  $('body,html').animate({
    scrollTop : 0
  }, 1000);
  return false;
});

$(function() {
  //查找h1-h6  
  var i = 1;
  var navToc = "";
  var navToc = "";
  $(".news_infos :header").each(function() {
    navToc += '<li class="nav-item nav-level-4" id="#nav1_' + i + '"><a class="nav-link" ><span class="nav-number">' + i + '.</span> <span class="nav-text">' + $(this).text() + '</span></a></li>';
    $("#nav1_" + i).css({
      'border-left' : '5px solid #FF926F',
      'background-color' : ' #f6f6f6',
      padding : '7px 20px',
      margin: '12px 0'
    });
    i++;
  });
  $(".nav1").html(navToc);
});
var count = 1;
var width = window.innerWidth || document.documentElement.clientWidth;

if (width < 700) {
  $(".tool-box").css("display", "none");
}
$(window).scroll(function() {
  if ($(document).scrollTop() > 20 && count == 1) {
    $(".dj").css("display", "block");
    initBlogByClick();
    count++;
  }
  if ($(document).scrollTop() > 1200 && width > 700) {
    $(".top").addClass('cd-is-visible fadeIn');
    $(".fixed-menu-list").css("display", "block");
  } else {
    $(".top").removeClass('cd-is-visible fadeOut');
    $(".fixed-menu-list").css("display", "none");
  }
});


$(document).ready(function() {
  if ($(".newsview h1").text() != "404") {
    Format();
    Tags();
    selectPrevBlog();
    selectNextBlog();
    initBlogByRel(); //初始化相关文章
  }
  initBlogByLike();
  setTimeout(function() {
    $(".ds").css("opacity", "1");
  }, 1000);
  var topId = $(".nav-item"); /*获取目录点击区域*/
  topId.click(function() {
    var topId = $(this).attr("id");
    $('body,html').animate({
      scrollTop : $(topId).offset().top
    }, 800);
    return false;
  });
  
//登录输入框效果
	$('.form_text_ipt input').focus(function(){
		$(this).parent().css({
			'box-shadow':'0 0 3px #bbb',
		});
	});
	$('.form_text_ipt input').blur(function(){
		$(this).parent().css({
			'box-shadow':'none',
		});
		//$(this).parent().next().hide();
	});
	
});
var Tags = function() {
  var tag = $(".tag").val();
  var keyword = "";
  $(".newsview").find(".tags").html("");
  if (tag != '' && tag != null) {
    if (tag.search(';') != -1) {
      var strs = new Array();
      strs = tag.split(";");
      for (var i = 0; i < strs.length && strs[i] != ''; i++) {
        keyword += '<a href="#">' + strs[i] + '</a>';
      }
    } else {
      keyword = '<a href="#">' + tag + '</a>';
    }
  }
  $(".newsview").find(".tags").append(keyword);
}

var selectPrevBlog = function() {
  var id = $(".id").val();
  var params = {
    id : id - 1
  };
  $.ajax({
    url : '../selectPrevBlog',
    type : 'get',
    data : params,
    dataType : 'json',
    success : function(data) {
      var preTitle = "";
      if (data.status == 200) {
        var id = data.blog.id.toString(8) * data.blog.id;
        preTitle = '<a href="../find/' + id + '.html">' + data.blog.title + '</a>';
      } else {
        preTitle = '<span>无</span>';
      }
      $(".pre").html(preTitle);
    },
    error : function() {
      layer.msg('加载的太快啦', {
        icon : 2
      });
    }
  });

};

var selectNextBlog = function() {
  var vid = $(".id").val();
  var id = parseInt(vid) + 1;
  var params = {
    id : id
  };
  $.ajax({
    url : '../selectNextBlog',
    type : 'get',
    data : params,
    dataType : 'json',
    success : function(data) {
      var nextTitle = '';
      if (data.status == 200) {
        var sid = data.blog.id.toString(8) * data.blog.id;
        nextTitle = '<a href="../find/' + sid + '.html">' + data.blog.title + '</a>';
      } else {
        nextTitle = '<span>无</span>';
      }
      $(".next").html(nextTitle);
    },
    error : function() {
      layer.msg('加载的太快啦', {
        icon : 2
      });
    }
  });

};

//初始化相关文章
var initBlogByRel = function() {
  var params = {
    pageSize : 6,
    page : 1,
    'type.id' : $(".typeId").val(),
  };
  $.ajax({
    url : '../selectGroupLikeBlogListByPage',
    type : 'get',
    data : params,
    dataType : 'json',
    success : function(data) {
      var relBlog = '';
      var data = data.blogList;
      for (var i = 0; i < data.length; i++) {
        var id = data[i].id.toString(8) * data[i].id;
        relBlog += '<li><i style="color:#5788aa" class="fa fa-paperclip"></i> <a href="' + id + '.html" title="' + data[i].title + '">' + data[i].title + '</a></li>'
      }
      // 初始化数据
      $(".otherlink").find("ul").html(relBlog);
    },
    error : function() {
      layer.msg('加载的太快啦', {
        icon : 2
      });
    }
  });
};

//初始化推荐
var initBlogByLike = function() {
  //设置参数
  var params = {
    pageSize : 5,
    page : 1,
    isrecommend : 1 //1 表示推荐
  };
  $.ajax({
    url : '../selectGroupLikeBlogListByPage',
    type : 'get',
    data : params,
    dataType : 'json',
    success : function(data) {
      var likeBlog = '';
      var data = data.blogList;
      var time = '';
      for (var i = 0; i < data.length; i++) {

        var id = data[i].id.toString(8) * data[i].id;
        time = i * 0.05;
        likeBlog += '<li style="animation-delay:0.' + i + 's" class="animated fadeIn"><b><a href="../find/' + id + '.html">'
          + data[i].title
          + '</a></b><p><i><img src="' + data[i].images + '"></i><span>'
          + data[i].introduction + '<span></p></li>'
      }
      // 初始化数据
      $(".paihang").find(".like").html(likeBlog);
    },
    error : function() {
      layer.msg('加载的太快啦', {
        icon : 2
      });
    }
  });
};

//初始化点击排行
var initBlogByClick = function() {
  //设置参数
  var params = {
    pageSize : 5,
    page : 1,
    sort : "clickNum", //按点击量排序,默认按时间
  };
  $.ajax({
    url : '../selectGroupLikeBlogListByPage',
    type : 'get',
    data : params,
    dataType : 'json',
    success : function(data) {
      var clickBlog = '';
      var data = data.blogList;
      var time = '';
      for (var i = 0; i < data.length; i++) {

        var id = data[i].id.toString(8) * data[i].id;
        time = i * 0.05;
        clickBlog += '<li style="animation-delay:0.' + i + 's" class="animated fadeIn"><b><a href="../find/' + id + '.html">'
          + data[i].title
          + '</a></b><p><i><img src="' + data[i].images + '"></i><span>'
          + data[i].introduction + '</span></p></li>'
      }
      // 初始化数据
      $(".paihang").find(".click").html(clickBlog);
    },
    error : function() {
      layer.msg('加载的太快啦', {
        icon : 2
      });
    }
  });
};


//格式化时间
var Format = function() {
  var datetime = $(".addtime").val();
  var month = new Array();
  month["Jan"] = '01';
  month["Feb"] = '02';
  month["Mar"] = '03';
  month["Apr"] = '04';
  month["May"] = '05';
  month["Jun"] = '06';
  month["Jul"] = '07';
  month["Aug"] = '08';
  month["Sep"] = '09';
  month["Oct"] = 10;
  month["Nov"] = 11;
  month["Dec"] = 12;
  var arr = new Array();
  arr = datetime.split(" ");
  var fmt = arr[5] + '-' + month[arr[1]] + '-' + arr[2];
  $(".au02").html(fmt);
}

//从缓存中获取数据并渲染
let msgBoxList = JSON.parse(window.localStorage.getItem('msgBoxList')) || [];


//点击小图片，显示表情
$(".bq").click(function (e) {
	$(".face").slideDown(); //慢慢向下展开
	e.stopPropagation(); //阻止冒泡事件
});

//在桌面任意地方点击，关闭表情框
$(document).click(function (e) {
	$(".face").slideUp(); //慢慢向上收
	
});

//点击小图标时，添加功能
$(".face ul li").click(function () {
	let simg = $(this).find("img").clone();
	$(".message").append(simg); //将表情添加到输入框
});

//点击发表按扭，发表内容
$("span.submit").click(function () {
	
	let txt = $(".message").html(); //获取输入框内容
	if (!txt) {
		$('.message').focus(); //自动获取焦点
		return;
	}
	/* article="${blog.id }" author="${blog.createblogerid }*/
	var wenzhangid = $(this).attr("article");
	var toblogerid = $(this).attr("author");
	
	var comment = {
			totBlogerId:toblogerid,
			tBlogId:wenzhangid,
			createTime:new Date(),
			commentsContent:txt,
			parentCommId:null
	}
	
	insertcomment(comment,$('.msgCon'));
	$(".message").html("");
})

//一级评论回复按钮
$("body").on('click', '.commentsubmit', function (e) {
		var obj = $(this);
		var cdjbobj = obj.parent().parent().parent();
		//获得评论级别
		var level = cdjbobj.attr("level");
		//评论正文
		var txt = obj.prev().val();
		
		if (!txt) {
			obj.prev().focus(); //自动获取焦点
			return;
		}
		
		//获得文章id 和被评论人id
		var article = obj.attr("article");
		var author = obj.attr("author");
		
		var comment = {
				totBlogerId:author,
				tBlogId:article,
				createTime:new Date(),
				commentsContent:txt,
				parentCommId:level
		}
		
		insertcomment(comment,obj.parent().parent().next().next());
		
		obj.parent().slideUp();
		obj.prev().val("")
})

//点击二级评论回复按钮提交数据
$("body").on('click', '.childcommentsubmit', function (e) {
		
		var obj = $(this);
		var cdjbobj = obj.parent().parent().parent().parent();
		//得到评论的级别
		var level = cdjbobj.attr("level");
		//评论正文
		var txt = obj.prev().val();
		
		if (!txt) {
			obj.prev().focus(); //自动获取焦点
			return;
		}
		
		//
		var article = obj.attr("article");
		var author = obj.attr("author");
		
		var comment = {
				totBlogerId:author,
				tBlogId:article,
				createTime:new Date(),
				commentsContent:txt,
				parentCommId:level
		}
		
		insertcomment(comment,obj.parent().parent().parent());
		
		 obj.parent().slideUp();
		obj.prev().val("")
})

//删除当前数据
$("body").on('click', '.del', function (){
	var thisobj  = $(this);
	var tier = thisobj.attr("tier");
	var index = thisobj.attr("delindex");
	var author = thisobj.attr("author");
	var commenthead = "";
	var commentcontent = "";
	if(tier == 2 ){
		commenthead = thisobj.parent().parent();
		commentcontent = commenthead.next();
	}else{
		commenthead = thisobj.parent().parent().parent();
	}
	 
	
	var symbol = delcomment(index,author);
	if(symbol.success == true ){
		if(tier == 2){
			commentcontent.remove();
			commenthead.remove();
		}else{
			commenthead.remove();
		}
	}else{
		if(symbol.status == 5000 ){
			
			alert(symbol.message);
		}
	}
})

$("body").on('click', '.reply', function (e) {
	
	$(".face").slideUp(); //表情包慢慢向上收
	
	var replydiv = $(this).parent().next();
	//自身的isshow
	var isshow = replydiv.css("display");
	var ddd = $('.replydiv');
	for(var i =0;i<ddd.length;i++){
		var yangshi = $(ddd[i]).css("display");
		if(!($(ddd[i])== replydiv)){
			$(ddd[i]).slideUp();
			$(ddd[i]).children().first().val("");
		}
	}
	
	if(isshow == "none"){
		replydiv.slideDown();
	}else{
		replydiv.slideUp();
		$(replydiv).children().first().val("");
	}
	e.stopPropagation(); //阻止冒泡事件
})

$("body").on('click', '#denglu', function (){
	var username = $("#username").val();
	var password = $("#password").val();
	
	nologinislogin(username,password);
})

//渲染html
function innerHTMl(List) {
	List = List || []
	
	for(var i= 0;i<List.length;i++){
		
		var timestamp = eval(List[i].createTime);
		var childComment = (List[i].childComment);
		var date = new Date(timestamp);
		date = formatdate(date);
		
		let str =
			`<div class='msgBox' level="`+List[i].id+`">
				<div class="head">
					<div class="headUrl" >
						<img src='`+List[i].bloger.photo+`' width='50' height='50'>
						<div>
							<span class="title">`+List[i].bloger.username+`</span>
							<span class="time">`+date+`</span>
						</div>
						<a class="reply">回复</a>
						<a class="del" delindex="`+List[i].id+`" author="`+List[i].tBlogerId+`" tier="1">删除</a>
					</div>
					<div class="replydiv" style="height:35px; display:none;">
							<input type="text" style="width:87%;  height:30px; line-height:30px; font-size:15px; "/>
							<span class='commentsubmit'  article="`+List[i].tBlogId+`" author="`+List[i].tBlogerId+`" >回复</span>
					</div>
				</div>
				<div class='msgTxt'>`+List[i].commentsContent+`</div>
				<div class="child" style="width:90%;  float:right; margin-right:25px;">`
				+innerchildHTML(childComment)+		
			`</div>
		 </div>`
		$(".msgCon").prepend(str);
	}
}

$(function (){
	var id = $("#blogid").html();
	if(id != null && id !="" && id != undefined ){
		$.ajax({
			url : getRootPath()+'/queryComments',
			type : 'post',
			data : {
				id:id
			},
			async : false,
			datatype:'json',
			success : function(resultdata) {
				innerHTMl(resultdata);
			},
			error : function() {
				alert("系统出错");
			}
		});
	}
	
})
/*获得当前项目名*/
function getRootPath(){
		//获取当前网址，
		var curWwwPath=window.document.location.href;
		//获取主机地址之后的目录
		var pathName=window.document.location.pathname;
		var pos=curWwwPath.indexOf(pathName);
		//获取主机地址，
		var localhostPaht=curWwwPath.substring(0,pos);
		//获取带"/"的项目名，
		var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
		return(projectName);
	}

function formatdate(date){
	if(date == null || date == undefined ){
		return ;
	}
	var year = date.getFullYear();
	var month = date.getMonth()+1;
	var day = date.getDate();
	
	var hours = date.getHours();
	var minutes = date.getMinutes();
	var seconds = date.getSeconds();
	
	return year+"-"+month+"-"+day+"  "+hours+":"+minutes+":"+seconds;
}
function innerchildHTML(List){
	var child = "";
	if(List == null || List == []){
		return child;
	}
	
	for(var i = 0;i<List.length;i++){
		var timestamp = eval(List[i].createTime);
		var date = new Date(timestamp);
		date = formatdate(date);
		var str =
		`<div class="childhead" >
			<div class="childheadUrl">
				<img src='`+List[i].bloger.photo+`' width='40' height='40'>
				<div>
					<span class="childtitle">`+List[i].bloger.username+` 回复:  `+List[i].tobloger.username+`</span>
					<span class="childtime">`+date+`</span>
				</div>
				<a class="reply">回复</a>
				<a class="del" delindex="`+List[i].id+`" author="`+List[i].tBlogerId+`" tier="2">删除</a>
			</div>
			<div class="replydiv" style="height:35px; display:none;">
				<input type="text" style="width:87%;  height:30px; line-height:30px; font-size:15px; "/>
				<span  class='childcommentsubmit' article="`+List[i].tBlogId+`" author="`+List[i].tBlogerId+`">回复</span>
			</div>
		</div>
		<div class='childmsgTxt'>`
			+List[i].commentsContent+
		`</div>`
	child = child+str;
	}
	return child;
}
//向后台提交评论数据（插入评论）即发送ajax。
function insertcomment(comment,triggernode){
	$.ajax({
		url : getRootPath()+'/inserComment',
		type : 'post',
		contentType: "application/json;charset=UTF-8",
		data : JSON.stringify({
			totBlogerId:comment.totBlogerId,
			tBlogId:comment.tBlogId,
			createTime:comment.createTime,
			commentsContent:comment.commentsContent,
			parentCommId:comment.parentCommId
		}),
		async :true,
		datatype:'json',
		success : function(resultdata) {
			var status = resultdata.status
			if(status == 4000 ){
				openlogin();
			}
			if(status == 2000){
				var resultobj = resultdata.resultobj;
				var comment = {
						//评论id
						id:resultobj.id,
						//被评论人id
						totBlogerId:resultobj.tBlogerId,
						//哪个博客id
						tBlogId:resultobj.tBlogId,
						//创建时间
						createTime:resultobj.createTime,
						//评论正文
						commentsContent:resultobj.commentsContent,
						//评论人
						bloger:resultobj.bloger,
						//被评论人
						tobloger:resultobj.tobloger,
						//父级菜单
						parentCommId:resultobj.parentCommId
				}
				if(comment.parentCommId != null || comment.parentCommId != undefined){
					var insercommentsuccessstr = insertcommsuccessoftoo(comment);
					$(triggernode).append(insercommentsuccessstr);
				}else{
					var insercommentsuccessstr = insertcommsuccessofnoe(comment);
					$(triggernode).append(insercommentsuccessstr);
				}
				
			}
			
			
		},
		error : function() {
			alert("系统出错");
		}
	})
}
//删除评论
function delcomment(delindex,author){
	var symbol = {
			success:false,
			status:5000,
			message:"删除失败"
		}
	$.ajax({
		url : getRootPath()+'/delcomment',
		type : 'post',
		data :{
			delindex:delindex,
			author:author
		},
		async :false,
		datatype:'json',
		success : function(resultdata) {
			var status = resultdata.status ;
			var message = resultdata.message;
			if(status == 4000 ){
				openlogin();
				symbol.status = status;
				symbol.message = message;
			}
			if(status == 2000 ){
				symbol.success=true;
				symbol.message = message;
				symbol.status = status;
			}
			if(status == 4005){
				symbol.status = status;
				symbol.message = message;
			}
		},
		error : function() {
			alert("系统出错");
		}
	})
	
	return symbol;
}
//未登录弹出登录框
function openlogin(){
	var html = 
		`<div class="login_box">	
			<div class="login_form">
				<div class="login_title">
					请先登录
				</div>
				<div id="formdiv">
					
					<div class="form_text_ipt">
						<input name="username" id="username" type="text" placeholder="用户名">
					</div>
					<div class="ececk_warning"><span>用户名不能为空</span></div>
					<div class="form_text_ipt">
						<input name="password" id="password" type="password" placeholder="密码">
					</div>
					<div class="ececk_warning"><span>密码不能为空</span></div>
					<div class="form_check_ipt">
						<div class="left check_left">
							<label><input name="" type="checkbox"> 下次自动登录</label>
						</div>
						<div class="right check_right">
							<a href="#">忘记密码</a>
						</div>
					</div>
					<div class="form_btn">
						<button type="button" id="denglu">登录</button>
					</div>
					<div class="form_reg_btn">
						<span>还没有帐号？</span><a href="`+getRootPath()+"/login"+`">马上注册</a>
					</div>
				</div>
			</div>
		</div>`
			layer.open({
				type:1,
				content:html,
				title:false,
				shadeClose:true,
				scrollbar:false
				})
}

//二级评论
function insertcommsuccessoftoo(comment){
	var str =
		`<div class="childhead" >
			<div class="childheadUrl">
				<img src='`+comment.bloger.photo+`' width='40' height='40'>
				<div>
					<span class="childtitle">`+comment.bloger.username+` 回复:  `+comment.tobloger.username+`</span>
					<span class="childtime">`+formatdate(new Date(eval(comment.createTime)))+`</span>
				</div>
				<a class="reply">回复</a>
				<a class="del" delindex="`+comment.id+`" author="`+comment.totBlogerId+`" tier="2">删除</a>
			</div>
			<div class="replydiv" style="height:35px; display:none;">
				<input type="text" style="width:87%;  height:30px; line-height:30px; font-size:15px; "/>
				<span id="abc" class='childcommentsubmit' article="`+comment.tBlogId+`" author="`+comment.totBlogerId+`">回复</span>
			</div>
		</div>
		<div class='childmsgTxt'>`
			+comment.commentsContent+
		`</div>`
			return str;
}
//一级评论
function insertcommsuccessofnoe(comment){
	
	var str =
		`<div class='msgBox' level="`+comment.id+`">
			<div class="head">
				<div class="headUrl" >
					<img src='`+comment.bloger.photo+`' width='50' height='50'>
					<div>
						<span class="title">`+comment.bloger.username+`</span>
						<span class="time">`+formatdate(new Date(eval(comment.createTime)))+`</span>
					</div>
					<a class="reply">回复</a>
					<a class="del" delindex="`+comment.id+`" author="`+comment.totBlogerId+`" tier="1">删除</a>
				</div>
				<div class="replydiv" style="height:35px; display:none;">
						<input type="text" style="width:87%;  height:30px; line-height:30px; font-size:15px; "/>
						<span class='commentsubmit'  article="`+comment.tBlogId+`" author="`+comment.totBlogerId+`" >回复</span>
				</div>
			</div>
			<div class='msgTxt'>`+comment.commentsContent+`</div>
			<div class="child" style="width:90%;  float:right; margin-right:25px;"></div>
	 </div>`
	return str;
}

function nologinislogin(username,password){
	
	
	if((username != null || username != '') && (password != null || password != '')){
		$.ajax({
			url : getRootPath()+'/checkLogin',
			type : 'post',
			data :{
				username:username,
				password:password
			},
			async :false,
			datatype:'json',
			success : function(resultdata) {
				var status = resultdata.status ;
				var message = resultdata.message;
				if(status == 200){
					layer.close(layer.index);
					window.location.reload();
				}else{
					alert(message);
				}
				
			},
			error : function() {
				alert("系统出错");
			}
		})
	}else{
		alert("请输入账号和密码！！");
	}
	
}